import { LogService } from '../logService';

export class ChatGLMAgent {
    constructor() {
        this.logger = new LogService('ChatGLMAgent');
        this.accessToken = null;
        this.tokenExpireTime = null;
        this.baseUrl = 'https://chatglm.cn/chatglm/assistant-api/v1';
    }

    /**
     * 获取配置信息
     * @returns {Promise<{apiKey: string, apiSecret: string, assistantId: string, enabled: boolean}>}
     */
    async getConfig() {
        this.logger.debug('获取智谱轻言配置');
        const config = await chrome.storage.sync.get([
            'chatglmEnabled',
            'chatglmApiKey',
            'chatglmApiSecret',
            'assistantId'
        ]);

        return {
            enabled: config.chatglmEnabled || false,
            apiKey: config.chatglmApiKey || '',
            apiSecret: config.chatglmApiSecret || '',
            assistantId: config.assistantId || ''
        };
    }

    /**
     * 获取访问令牌
     * @returns {Promise<string>}
     */
    async getAccessToken() {
        try {
            // 检查是否已有有效的token
            if (this.accessToken && this.tokenExpireTime && Date.now() < this.tokenExpireTime) {
                this.logger.debug('使用缓存的访问令牌');
                return this.accessToken;
            }

            const config = await this.getConfig();
            if (!config.enabled) {
                throw new Error('智谱轻言服务未启用');
            }

            this.logger.debug('开始获取新的访问令牌');
            const response = await fetch(`${this.baseUrl}/get_token`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    api_key: config.apiKey,
                    api_secret: config.apiSecret
                })
            });

            const data = await response.json();
            
            if (!response.ok) {
                this.handleApiError(response.status, data);
            }

            if (data.result && data.result.access_token) {
                this.accessToken = data.result.access_token;
                // 设置过期时间为9.5天（为保险起见比10天少一些）
                this.tokenExpireTime = Date.now() + (9.5 * 24 * 60 * 60 * 1000);
                this.logger.debug('成功获取新的访问令牌', { expireTime: new Date(this.tokenExpireTime) });
                return this.accessToken;
            }

            throw new Error('获取访问令牌失败：返回数据格式错误');
        } catch (error) {
            this.logger.error(error, '获取访问令牌失败');
            throw error;
        }
    }

    /**
     * 处理API错误
     * @param {number} status HTTP状态码
     * @param {Object} data 响应数据
     */
    handleApiError(status, data) {
        let errorMessage = '未知错误';
        
        if (status === 403 && data.status === 1001) {
            errorMessage = 'API Key已被禁用';
        } else if (status === 401 && data.status === 1002) {
            errorMessage = 'API Key或Secret验证失败';
        } else {
            errorMessage = `请求失败: ${data.message || '未知错误'}`;
        }

        throw new Error(errorMessage);
    }

    /**
     * 发送消息并获取响应
     * @param {string} prompt 用户输入的消息
     * @param {string} [conversationId] 会话ID（可选）
     * @returns {Promise<string>}
     */
    async sendMessage(prompt, conversationId = null) {
        try {
            const config = await this.getConfig();
            if (!config.enabled || !config.assistantId) {
                throw new Error('智谱轻言服务未正确配置');
            }

            const accessToken = await this.getAccessToken();
            this.logger.debug('开始发送消息', { prompt, conversationId });

            const response = await fetch(`${this.baseUrl}/stream`, {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${accessToken}`,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    assistant_id: config.assistantId,
                    prompt,
                    conversation_id: conversationId
                })
            });

            if (!response.ok) {
                const errorData = await response.json();
                this.handleApiError(response.status, errorData);
            }

            // 处理SSE流式响应
            const reader = response.body.getReader();
            let result = '';

            while (true) {
                const { done, value } = await reader.read();
                if (done) break;

                // 将二进制数据转换为文本
                const chunk = new TextDecoder().decode(value);
                const lines = chunk.split('\n');

                for (const line of lines) {
                    if (line.startsWith('data:')) {
                        const data = JSON.parse(line.slice(5));
                        const content = this.handleResponseContent(data);
                        if (content) {
                            result = content; // 保存最新的内容
                        }
                    }
                }
            }

            this.logger.debug('消息发送完成', { result });
            return result;
        } catch (error) {
            this.logger.error(error, '发送消息失败');
            throw error;
        }
    }

    /**
     * 处理响应内容
     * @param {Object} data 响应数据
     * @returns {string|null}
     */
    handleResponseContent(data) {
        const message = data.message;
        if (!message || !message.content) return null;

        const content = message.content;
        switch (content.type) {
            case 'text':
                return content.text || '';
            case 'image':
                return content.image?.map(img => img.image_url).join('\n') || '';
            case 'code':
                return content.code || '';
            case 'execution_output':
                return content.content || '';
            case 'system_error':
                this.logger.error(new Error(content.content), '系统错误');
                return null;
            default:
                return null;
        }
    }
} 